package com.lzh.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.commonutils.JwtUtils;
import com.lzh.commonutils.Md5Util;
import com.lzh.commonutils.RandomUtil;
import com.lzh.edu.entity.AdUser;
import com.lzh.edu.mapper.AdUserMapper;
import com.lzh.edu.service.AdUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author lizuhu
 * @date 2021/6/27 16:19
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private AdUserMapper adUserMapper;

    @Override
    public boolean saveUser(AdUser adUser) {
        //随机生成盐值
        String salt = RandomUtil.random(10);
        //为用户设置盐值
        adUser.setSalt(salt);
        //使用md5加盐值对密码进行加密
        String pwd = Md5Util.toMD5(adUser.getPassword(), salt);
        adUser.setPassword(pwd);
        Integer i = adUserMapper.insert(adUser);
        if (i != null && i != 0) {
            return true;
        } else {
        return false;
        }
    }

    @Override
    public String login(AdUser adUser) {
        //根据条件查询用户
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",adUser.getUsername());
        AdUser user = adUserMapper.selectOne(queryWrapper);
        if (user == null) {
            return null;
        }
        //将用户提交的用户密码跟数据库的密码进行比对
        String pwd = Md5Util.toMD5(adUser.getPassword(), user.getSalt());
        if (!pwd.equals(user.getPassword())) {
            return null;
        }
        //登录成功，生成令牌
        String token = JwtUtils.createToken(user.getId().toString(), user.getUsername());
        if (token != null) {
        return token;
        } else {
            return null;
        }
    }

    @Override
    public AdUser getInfo(String userId) {
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",userId);
        AdUser adUser = adUserMapper.selectOne(queryWrapper);
        if (adUser == null) {
            return null;
        }
        adUser.setPassword("****");
        return adUser;
    }

}
